package com.lyf.common.serialize;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.lyf.common.api.ResultCode;
import com.lyf.common.exception.ApiException;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lyf
 * @since 2020/10/13 19:28
 */
public class DeserializeToTimeStamp extends JsonDeserializer<Long> {

    @Override
    public Long deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        String text = jsonParser.getText();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            if (StringUtils.isBlank(text)){
                return null;
            }
            Date date = format.parse(text);

            long timeStamp = date.getTime();

            return timeStamp;

        } catch (ParseException e) {
            throw new ApiException(ResultCode.DATE_PARSE_ERROR);
        }
    }
}
